package TCPEcho;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    private ServerSocket serverSocket = null;

    public Server() throws IOException {
        serverSocket = new ServerSocket(9090);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        while (true){
            Socket socket = serverSocket.accept();
            processConnection(socket);

        }
    }

    public String processConnection(Socket socket) throws IOException {
        try (InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while (true){
                Scanner scanner = new Scanner(inputStream);
                String request = scanner.next();
                String response = process(request);


                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
            }
        }finally {
            socket.close();
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.start();
    }
}
